package com.wnxy.sddfp.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class RatelimitConfig {
    /**
     * 根据IP限流，即以每秒内请求数按IP分组统计，超出限流的url请求都将返回429状态
     */
    @Bean
    public KeyResolver ipKeyResolver(){
       return new KeyResolver() {
           @Override
           public Mono<String> resolve(ServerWebExchange exchange) {
               //获取请求的IP地址
               String hostName = exchange.getRequest().getRemoteAddress().getHostName();
               //创建Mono发布者对象，发布数据源
               return Mono.just(hostName);
           }
       };
    }
}